package com.study_security.controller;

import com.study_security.domain.LoginUser;
import com.study_security.domain.ResponseResult;
import com.study_security.dto.MemberDTO;
import com.study_security.dto.ProjectDTO;
import com.study_security.entity.ProjectMember;
import com.study_security.service.MemberService;
import com.study_security.service.ProjectMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/members")
//@PreAuthorize("hasAnyAuthority('perm_review','perm_leader','perm_member')")
public class MemberController {

    @Autowired
    private MemberService memberService;
    @Autowired
    private ProjectMemberService projectMemberService;

    @PreAuthorize("hasAnyAuthority('perm_review','perm_leader')")
    @GetMapping
    public List<MemberDTO> getAllMembers() {
        return memberService.getAllMembers();
    }

    @GetMapping("/search")
    public List<MemberDTO> getProjectMembersAndTasks(@RequestParam String projectName) {
        return memberService.getProjectMembersAndTasks(projectName);
    }

    @PreAuthorize("hasAnyAuthority('perm_leader','perm_review')")
    @GetMapping("/projects")
    public List<ProjectDTO> getUserProjectsAndMembers(Authentication authentication) {
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        return memberService.getUserProjects(userId);
    }

    @GetMapping("/{projectId}/members")
    public List<MemberDTO> getProjectMembers(@PathVariable Long projectId) {
        return memberService.getMembersByProjectId(projectId);
    }

    @PreAuthorize("hasAuthority('perm_leader')")
    @PostMapping("/add")
    public String addProjectMembers(@RequestBody ProjectMember projectMember) {

        if (projectMemberService.projectMemberExists(projectMember.getProjectId(),projectMember.getMemberId())) {
            return "The member already exists, please select again.";
        }

      boolean isAdded=projectMemberService. addMemberToProject(projectMember);
        return isAdded ? "Member added successfully!" : "Failed to add Member.";
    }

    @PreAuthorize("hasAuthority('perm_leader')")
    @DeleteMapping("/remove")
    public ResponseEntity<String> removeProjectMember(@RequestParam Long projectId, @RequestParam Long memberId) {
        boolean isRemoved = projectMemberService.removeMemberFromProject(projectId, memberId);
        return isRemoved ? ResponseEntity.ok("Member removed successfully!") : ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed to remove member.");
    }



}
